package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminStyle.*;
import com.shop.entity.dto.AdminWares.*;
import com.shop.entity.pojo.*;
import com.shop.admin.mapper.*;
import com.shop.admin.service.StyleService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class StyleServiceImpl extends ServiceImpl<StyleMapper,Style> implements StyleService {

    @Autowired
    private CostMapper costMapper;

    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private ImagesMapper waresImagesMapper;
    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result saveOneStyle(AdminStyleSaveDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-添加商品款式");
        if (dto==null) {
            log.info("dto为空");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null) {
            log.info("该管理员不存在");
            Result.errorResult(Code.PARAM_INVALID);
        }
        List<Style> styleList = styleMapper.selectList(Wrappers.<Style>lambdaQuery().eq(Style::getStyleName, dto.getStyleName()).eq(Style::getWaresId, dto.getWaresId()));
        if (!CollectionUtils.isEmpty(styleList)||styleList.size()>Message.Check_Int_Null) {
            log.info("该数据已存在style:{}",styleList);
            return Result.errorResult(Code.DATA_EXIST);
        }
        Images waresImages = waresImagesMapper.selectById(dto.getStyleImagesId());
        if (waresImages==null) {
            log.info("未查询到该图片素材");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (dto.getCostMessage()==null||dto.getWaresPrice()==Message.Check_Int_Null) {
            log.info("商品价格参数为空");
            log.info("你需要为你的商品款式添加一个新的价格");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Style style=new Style();
        String styleImages = waresImages.getUrl();
        style= style.builder()
                .waresId(dto.getWaresId())
                .styleName(dto.getStyleName())
                .styleImages(styleImages)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int save = styleMapper.insert(style);
        if (save==Message.Check_Int_False) {
            log.info("添加失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        Cost cost=new Cost().builder()
                .costMessage(dto.getCostMessage())
                .waresPrice(dto.getWaresPrice())
                .waresId(dto.getWaresId())
                .styleId(style.getId())
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int insert = costMapper.insert(cost);
        if (insert==Message.Check_Int_False) {
            log.info("添加失败");
            log.info("开始删除商品款式");
            int deleteById = styleMapper.deleteById(style.getId());
            if (deleteById==Message.Check_Int_False) {
                log.info("清除添加的商品款式失败");
                return Result.errorResult(Code.SERVER_ERROR);
            }
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理添加款式进程完成，总耗时:{}",(end-start));

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getWaresDetail(AdminWaresStyleListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-商品相关款式");
        if (dto.getWaresId()==null) {
            log.info("未接收到前端传递的参数");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<Style> page=new Page<>(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Wares_Style+dto.getWaresId();
        Page<Style> check = (Page<Style>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理查看商品相关款式列表进程完成，总耗时:{}",(end-start));
            return result;
        }
        log.info("浏览数据库");
        Page<Style> value = styleMapper.stylePageByWaresId(page, dto.getWaresId());
        redisTemplate.opsForValue().set(key,value);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理查看商品相关款式列表进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Override
    public Result updateStyle(AdminStyleUpdateDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-修改商品款式");
        if (dto==null||dto.getStyleId()==null) {
            log.info("未获取到前端传递的参数");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getId, adminId));
        if (adminUser==null||adminId==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style oldStyle = styleMapper.selectById(dto.getStyleId());
        if (oldStyle==null) {
            log.info("未查询到你要修改的商品款式");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Long waresId=oldStyle.getWaresId();
        if (dto.getWaresId()!=null) {
            log.info("修改新的款式归属商品");
            Wares wares = waresMapper.selectOne(Wrappers.<Wares>lambdaQuery().eq(Wares::getId, dto.getWaresId()));
            if (wares==null) {
                log.info("未找到你要修改的归属商品");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            waresId=wares.getId();
        }
        String styleName=oldStyle.getStyleName();
        if (dto.getStyleName()!=null) {
            log.info("修改新的款式名称");
            List<Style> styles = styleMapper.selectList(Wrappers.<Style>lambdaQuery().eq(Style::getStyleName, dto.getStyleName()));
            if (styles==null) {
                log.info("该商品款式数据已存在");
                return Result.errorResult(Code.DATA_EXIST);
            }
            styleName= dto.getStyleName();
        }

        String styleImages=oldStyle.getStyleImages();
        if (dto.getStyleImagesId()!=null) {
            Images waresImages = waresImagesMapper.selectById(dto.getStyleImagesId());
            if (waresImages==null) {
                log.info("未查询到该图片素材");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            styleImages=waresImages.getUrl();
        }
        Style style=new Style();
        style= style.builder()
                .waresId(waresId)
                .styleName(styleName)
                .styleImages(styleImages)
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean update = update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        if (!update) {
            log.info("未修改成功");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品款式进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result removeStyle(AdminStyleRemoveDto dto) {
        long start = System.currentTimeMillis();
        log.info("删除商品款式");
        if (dto==null||dto.getStyleId()==null||dto.getRemoveMemo()==null) {
            log.info("未接收到前端传来的数据");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            log.info("未查询到该管理员");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style style = styleMapper.selectById(dto.getStyleId());
        if (style==null) {
            log.info("未查询到需要删除的商品款式");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        List<Cost> costList = costMapper.selectList(Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, dto.getStyleId()));
        if (!CollectionUtils.isEmpty(costList)||costList.size()>Message.Check_Int_Null) {
            if (dto.getRemoveRelated().equals("true")) {
                log.info("开始删除关联的价格");
                Cost cost=new Cost().builder().removeAdmin(adminUser.getName()).removeMemo(dto.getRemoveMemo()).build();
                int update = costMapper.update(cost, Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, dto.getStyleId()));
                int delete = costMapper.delete(Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, dto.getStyleId()));
                if (update==Message.Check_Int_False||delete==Message.Check_Int_False) {
                    log.info("价格删除失败");
                    return Result.errorResult(Code.SERVER_ERROR);
                }
            }else if (dto.getRemoveRelated().equals("false")){
                log.info("该商品款式有残留的价格套餐，请优先删除");
                return Result.errorResult(Code.DATA_EXIST);
            }else {
                return Result.errorResult(Code.PARAM_INVALID);
            }
        }
        Style newStyle=new Style();
        newStyle= newStyle.builder()
                .removeMemo(dto.getRemoveMemo())
                .removeAdmin(adminUser.getName()).build();
        boolean update = update(newStyle, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        if (!update) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        int delStyle = styleMapper.deleteById(dto.getStyleId());
        if (delStyle==Message.Check_Int_False) {
            log.info("删除失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理删除商品款式进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<Style> updateGetStyle(AdminStyleUpdateForGetDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-修改商品款式数据回显");
        if (dto.getStyleId()==null) {
            log.info("未接收到前端传来的商品款式ID");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Style style = getOne(Wrappers.<Style>lambdaQuery().eq(Style::getId, dto.getStyleId()));
        if (style==null) {
            log.info("未查询到该商品款式数据");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理修改商品款式回显进程完成，总耗时:{}",(end-start));
        return Result.okResult(style);
    }

    @Override
    public Result getStyleList(AdminStyleListDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-款式列表");
        dto.checkParam();
        Page<Style> page=new Page<>(dto.getPage(),dto.getSize());
        String key=Message.Admin_key_Style_All;
        Page<Style> check = (Page<Style>) redisTemplate.opsForValue().get(key);
        if (check!=null&&!check.equals("")) {
            log.info("浏览缓存");
            Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) check.getTotal());
            result.setData(check.getRecords());
            long end = System.currentTimeMillis();
            log.info("后台管理款式列表进程完成，总耗时:{}",(end-start));
            return result;
        }
        Page<Style> value = styleMapper.getAllByPage(page, dto);
        redisTemplate.opsForValue().set(key,value);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        long end = System.currentTimeMillis();
        log.info("后台管理款式列表进程完成，总耗时:{}",(end-start));
        return result;
    }

    @Override
    public Result openStyle(AdminStyleOpenDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-恢复商品款式");
        if (dto.getStyleId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        Style byId = styleMapper.getOne(dto.getStyleId());
        if (adminId==null||adminUser==null||byId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (byId.getIsDelete()==Message.Check_Int_Null) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        Style style=new Style();
        style= style.builder()
                .id(byId.getId())
                .removeMemo(Message.Remove_Null)
                .removeAdmin(Message.Remove_Null)
                .isDelete(Message.Delete_True)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean update = styleMapper.updateIsDelete(style);
        if (!update) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理恢复商品款式进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result pullStyle(AdminStylePullDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-下架商品款式");
        if (dto.getStyleId()==null||dto.getMemo()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if (adminUser==null||userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Style checkStyle = styleMapper.selectById(dto.getStyleId());
        if (checkStyle==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style style=new Style();
        Cost cost=new Cost();
        style= style.builder().state(Message.Pull).removeAdmin(adminUser.getName()).removeMemo(dto.getMemo()).build();
        cost= cost.builder().state(Message.Pull).removeAdmin(adminUser.getName()).removeMemo(dto.getMemo()).build();
        int pullStyle = styleMapper.update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        int pullCost = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getStyleId, dto.getStyleId()));
        if (pullStyle==Message.Check_Int_False||pullCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理下架商品款式进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result putStyle(AdminStylePutDto dto) {
        long start = System.currentTimeMillis();
        log.info("后台管理-上架商品款式");
        if (dto.getStyleId()==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if (adminUser==null||userId==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Style checkStyle = styleMapper.selectById(dto.getStyleId());
        if (checkStyle==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style style=new Style();
        Cost cost=new Cost();
        style= style.builder().state(Message.Put).saveAdmin(adminUser.getName()).saveTime(String.valueOf(LocalDateTime.now())).build();
        cost=cost.builder().state(Message.Put).saveAdmin(adminUser.getName()).saveTime(String.valueOf(LocalDateTime.now())).build();
        int pullStyle = styleMapper.update(style, Wrappers.<Style>lambdaUpdate().eq(Style::getId, dto.getStyleId()));
        int pullCost = costMapper.update(cost, Wrappers.<Cost>lambdaUpdate().eq(Cost::getStyleId, dto.getStyleId()));
        if (pullStyle==Message.Check_Int_False||pullCost==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("后台管理上架商品款式进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

}
